package com.youlu.campus.admin.item;

import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.ItemStockConfig;
import com.youlu.campus.entity.VO.req.ItemStockConfigVO;
import com.youlu.campus.service.item.ItemStockConfigService;
import com.youlu.campus.service.item.ItemStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Objects;

@RestController
public class ItemStockConfigController {
    @Autowired
    private ItemStockConfigService itemStockConfigService;
    @Autowired
    private ItemStockService itemStockService;

    @PostMapping("/item-stock-config/list")
    public RestResult list(@RequestBody @Valid ItemStockConfigVO req) {
        String comId = AuthUtils.getComId();
        Page<ItemStockConfig> users = itemStockConfigService.list(req);
        if (users == null) {
            PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
            users = PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0L);
        }
        for (ItemStockConfig config : users) {
            if (!Objects.isNull(config.getOperatorConfigedStock()) && Objects.isNull(config.getStock())) {
                config.setStock(config.getOperatorConfigedStock());
            }
            Integer s = itemStockService.getStock(config.getActivityId(), config.getCaInfoId());
            config.setOccupiedStock(s);
            if (Objects.nonNull(config.getStock())) {
                config.setMissStock(config.getStock() - s);
            }

        }
        return RestResultBuilder.builder().success().data(users).build();
    }

    @PostMapping("/item-stock-config/update")
    public RestResult list(@RequestBody @Valid ItemStockConfig req) {
        String comId = AuthUtils.getComId();
        boolean re = itemStockConfigService.update(req, AuthUtils.getLoginName(), AuthUtils.getLoginName());
        if (re) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @PostMapping("/item-stock-config/find-one")
    public RestResult findOne(@RequestParam("id") String id) {
        String comId = AuthUtils.getComId();
        ItemStockConfig re = itemStockConfigService.findOne(id);
        return RestResultBuilder.builder().success().data(re).build();
    }
}
